<template>
  <a-form :form="form" @submit="handleSubmit">
    <a-form-item label="标题" name="title">
      <a-input v-model:value="form.title" />
    </a-form-item>
    <a-form-item label="内容" name="content">
      <a-textarea v-model:value="form.content" />
    </a-form-item>
    <a-form-item label="作者" name="author_id">
      <a-select v-model:value="form.author_name">
        <a-select-option
          v-for="author in authors"
          :key="author.id"
          :value="author.name"
        >
          {{ author.name }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="分类" name="category_id">
      <a-select v-model:value="form.category_id">
        <a-select-option
          v-for="category in categories"
          :key="category.id"
          :value="category.id"
        >
          {{ category.name }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item>
      <a-button type="primary" html-type="submit">发布</a-button>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { ref } from "vue";
import { message } from "ant-design-vue";
import { addPassageApi, showCategoryApi } from "../utils/api.js";

// 获取浏览器当前登录用户的信息
const currentUser = localStorage.getItem("username");
const currentUserId = localStorage.getItem("id");

const authors = [{ id: currentUserId, name: currentUser }];

const categories = ref([]);

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const form = ref({
  title: "",
  content: "",
  author_name: currentUser, // 使用当前用户名作为初始值
  category_id: null,
});

const handleSubmit = () => {
  const currentDate = new Date();

  form.value.created_at = formatDate(currentDate);
  form.value.updated_at = formatDate(currentDate);
  form.value.published_at = formatDate(currentDate);

  console.log(form.value);
  addPassageApi({
    title: form.value.title,
    content: form.value.content,
    author: form.value.author_name,
    category_id: form.value.category_id,
    created_at: form.value.created_at,
    updated_at: form.value.updated_at,
    published_at: form.value.published_at,
  }).then((res) => {
    console.log(res);
  });

  message.success("文章发布成功");
};

// 获取showCategoryApi()接口返回的数据
showCategoryApi().then((res) => {
  categories.value = res.data.map((item) => ({
    id: item.id,
    name: item.name,
  }));
  console.log(categories.value);
});

</script>

<style scoped>
.a-form-item {
  margin-bottom: 24px;
}
</style>
